import 'dart:async';
import 'dart:io';

import 'package:redis/redis.dart';

class RedisUtils {
  static Command _command;
  static String host = "192.168.2.1";
  static int port = 6379;
  static PubSub _pubSub;
  static List<Function> _list = [];
  static RedisUtils _redisUtils;
  static RedisUtils newInstance() {
    if (_redisUtils == null) {
      _redisUtils = RedisUtils();
      _redisUtils.initRedis();
    }
    return _redisUtils;
  }

  void  initRedis() async {
  _command= await  RedisConnection()
        .connect(host, port);
  }

  static Future sendObject(List<String> command) async {
    if (_command == null) {
      return null;
    }
    Completer completer = Completer();
    _command
        .send_object(command)
        .then((value) => completer.complete(value))
        .catchError((onError) => completer.completeError(onError));
    return completer.future;
  }

  Future getReJson(String key, String path) async {
    if (_command == null) {
      print("Redis  Command is NULL ");
      return null;
    }
    return await sendObject(["json.get", key, path]);
  }

  static Future setReJson(String key, String path, String value) async {
    if (_command == null) {
      print("Redis  Command is NULL");
      return "";
    }
    return await sendObject(["json.set", key, path, value]);
  }

  static Future setRedis(String key, String value) async {
    if (_command == null) {
      print("Redis  Command is NULL");
      return "";
    }
    return await sendObject(["set", key, value]);
  }

  Future getRedis(String key) async {
    if (_command == null) {
      print("Redis  Command is NULL");
      return "";
    }
    return await sendObject(["get", key]);
  }

  static subscribeRedis(String topic, Function callBack) {
    if (_pubSub == null) {
      print("Redis  _pubSub is NULL");
      return null;
    }
    if (!_list.contains(callBack)) {
      _list.add(callBack);
    }
    _pubSub.subscribe([topic]);
  }

  static unSubscribeRedis(String topic) {
    if (_pubSub == null) {
      print("Redis  _pubSub is NULL");
      return "";
    }
    _pubSub.unsubscribe([topic]);
  }

  static removeCallBack(List<Function> callBacks) {
    callBacks.forEach((element) {
      if (_list.contains(element)) {
        _list.remove(element);
      }
    });
  }

  static publishRedis(String topic, String value) {
    if (_command == null) {
      print("Redis  Command is NULL");
      return "";
    }
    return sendObject(["publish", topic, value]);
  }
}

void main() {
  Timer.periodic(Duration(seconds: 2), (timer) {
    RedisUtils.newInstance().getRedis('name').then((value) => null);
  });
}